import { delChannelApi, getAllChannelListApi, getUserChannelListApi, postChannelApi } from "@/api/home"
import type { ChannelItem, ChannelsParams } from "@/types/http";
import { RootState } from "@/types/store";
import { isAuth } from "@/utils/token";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import DOMPurify from 'dompurify'

type State = {
  userChannels: ChannelItem[],
  allChannels: ChannelItem[],
}
const initialState: State = {
  userChannels: [],
  allChannels: []
}
const homeSlice = createSlice({
  name: 'home',
  initialState,
  reducers: {

  },
  extraReducers: (builder) => {
    builder.addCase(getChannelListAsync.fulfilled,
      (state, action) => {
        state.userChannels = action.payload.map(item => ({
          ...item,
          name: /[a-z]+/.test(item.name) ? item.name.toUpperCase() : item.name
        }))
      })

    builder.addCase(getAllChannelListAsync.fulfilled,
      (state, action) => {
        state.allChannels = action.payload.map(item => ({
          ...item,
          name: /[a-z]+/.test(item.name) ? item.name.toUpperCase() : item.name
        }))
      })

    builder.addCase(delChannelAsync.fulfilled, (state, action) => {
      const { payload } = action
      state.userChannels = Array.isArray(payload) ? payload : state.userChannels.filter(item => item.id !== payload)
    })

    builder.addCase(postChannelAsync.fulfilled, (state, action) => {
      state.userChannels.push(action.payload)
    })
  }
})

// 键名
const CHANNEL_KEY = 'm-toutiao-channel-key'

// 异步获取用户频道
export const getChannelListAsync = createAsyncThunk(
  'home/getChannelListAsync',
  async () => {
    // 登录了
    if (isAuth()) {
      // 请求用户频道
      const { data: {
        data: {
          channels
        }
      } } = await getUserChannelListApi()
      return channels
    }
    // 未登录

    // 取出本地数据
    const localChannels = JSON.parse(localStorage.getItem(CHANNEL_KEY) ?? '[]') as ChannelItem[]
    // 如果没有
    if (!localChannels.length) {
      // 请求默认列表
      const { data: {
        data: {
          channels
        }
      } } = await getUserChannelListApi()
      // 保存到本地
      localStorage.setItem(CHANNEL_KEY, JSON.stringify(channels))
      return channels
    }
    // 返回本地数据
    return localChannels
  }
)

// 异步获取所有频道
export const getAllChannelListAsync = createAsyncThunk(
  'home/getAllChannelListAsync',
  async () => {
    const { data: { data: { channels } } } = await getAllChannelListApi()
    return channels
  }
)

// 异步删除频道
export const delChannelAsync = createAsyncThunk(
  'home/delChannelAsync',
  async (id: number, { getState }) => {
    // 登录
    if (isAuth()) {
      // 从后台删除
      await delChannelApi(id)
      return id
    }
    const { home: { userChannels } } = getState() as RootState
    const newUserChannels = userChannels.filter(item => item.id !== id)
    localStorage.setItem(CHANNEL_KEY, JSON.stringify(newUserChannels))
    return newUserChannels
  }
)

// 新增频道
export const postChannelAsync = createAsyncThunk(
  'home/postChannelAsync',
  async (item: ChannelItem, { getState }) => {
    const { home: { userChannels } } = getState() as RootState
    // 登录了
    if (isAuth()) {
      const channels = [...userChannels, item].reduce(
        (sum,
          item, idx) => {
          sum.push({
            id: item.id,
            seq: idx + 1
          })
          return sum
        }, [] as ChannelsParams)
      await postChannelApi(channels)
    } else {
      localStorage.setItem(CHANNEL_KEY, JSON.stringify([
        ...userChannels,
        item
      ]))
    }
    return item
  }
)

export default homeSlice.reducer